<template>
  <view>
    <view class="addressEdit">
      <view class="content">
        <u-form ref="form1" label-position="left" :model="userInfo" label-width="80" :rules="rules" :label-style="labelStyle">
          <u-form-item label="收货人" prop="userInfo.name" border-bottom>
            <u-input v-model="userInfo.name" border="none" placeholder="输入收货人姓名" maxlength="32" />
          </u-form-item>
          <u-form-item label="手机号码" prop="userInfo.mobile" border-bottom>
            <u-input v-model="userInfo.mobile" type="idcard" border="none" placeholder="输入收货人手机号码" maxlength="11" />
          </u-form-item>
          <u-form-item label="固定电话" prop="userInfo.office_phone" border-bottom>
            <u-input v-model="userInfo.office_phone" type="idcard" border="none" placeholder="输入固定电话" maxlength="12" />
          </u-form-item>
          <u-form-item label="收货地址" prop="userInfo.address" border-bottom @click="showRegion">
            <!-- <u-input v-if="!userInfo.address" v-model="userInfo.address" border="none" disabled placeholder="选择省/市/区" />
            <view v-else>{{ userInfo.address }}</view> -->
            <view class="address-wrap">
              <view v-if="!userInfo.address" class="address_placeholder">选择省/市/区</view>
              <view v-else class="address_content">{{ userInfo.address }}</view>
              <!-- <u-icon slot="right" name="arrow-down" color="#AAAAAA" /> -->
              <view class="locate_wrap" @click.stop="handleOpenMap">
                <view class="locate_label">定位</view>
                <text class="location-icon font_family icon-position_tongyong_1" />
              </view>
            </view>
            <view v-if="cityInfo.cityCode && !cityInfo.streetId" class="warn_tips">请选择街道信息</view>
          </u-form-item>
          <u-form-item label="详细地址" prop="userInfo.detailAddress" class="areaInput">
            <u-textarea v-model="userInfo.detailAddress" style="color: #000000;" placeholder="输入详细地址" auto-height maxlength="32" />
          </u-form-item>
        </u-form>
        <view class="defaultSw">
          <view>设为默认地址 <u-switch v-model="isDefaultAddress" size="20" inactive-color="#E2E2E2" active-color="#FF5533" /></view>
          <text>提醒：下单会优先使用该地址</text>
        </view>
      </view>
      <view class="regionPopup">
        <u-popup :show="regionShow" :round="10" mode="bottom">
          <view class="title">
            选择地址<text class="icon-close font_family icon-guanbi_tongyong_1" @click="closeRegionFn" />
          </view>
          <view v-if="regionShow" :style="'height:' + height + 'px;'">
            <region :all-city="true" @getParams="getParams" />
          </view>
        </u-popup>
      </view>
      <view class="footerFaker" />
    </view>
    <!-- 底部按钮栏 -->
    <PageFooterBar
      only-btn
      :btn-list="btnList"
      @confirm="addressAdd"
      @cancel="() => { showModal = !showModal }"
      @export="handleExportFromWX"
      @click="addressAdd"
    />
    <u-modal
      width="540rpx"
      confirm-color="#FF5533"
      :show="showModal"
      :async-close="true"
      :show-cancel-button="true"
      @confirm="handleDeleteAddress"
      @cancel="() => { showModal = false }"
    >
      <view>确认要删除该地址吗？</view>
    </u-modal>
  </view>
</template>

<script>
import region from '@/components/region'
import { getNavHeight } from '@/common/common';
import { getAddressDetail, saveAddress, editAddress, deleteAddress, queryAddressLibraryInfo } from '@/api/address';
import PageFooterBar from '@/components/page-footer-bar'

export default {
  components: {
    region,
    PageFooterBar
  },
  data() {
    return {
      rules: {
        'name': {
          type: 'string',
          required: true,
          message: '请填写姓名',
          trigger: ['blur', 'change']
        }
      },
      userInfo: {
        name: '',
        mobile: '',
        office_phone: '',
        address: '',
        detailAddress: '',
      },
      isDefaultAddress: false,
      labelStyle: {
        'color': '#000000',
        'fontWeight': '500',
        'fontSize': '28rpx'
      },
      height: '',
      regionShow: false,
      id: '',
      cityInfo: {
        provinceId: '',
        provinceName: '',
        provinceCode: '',
        cityName: '',
        cityCode: '',
        cityId: '',
        districtCode: '',
        areaName: '',
        districtId: '',
        streetId: '',
        streetName: '',
        streetCode: ''
      },
      showModal: false,
      type: '',
      ship_add_id: ''
    }
  },
  computed: {
    btnList() {
      if (this.type == 'edit') { // 编辑按钮栏
        return [
          { name: '删除' },
          { name: '保存' }
        ]
      }
      // 新增按钮栏
      return [
        // #ifdef MP-WEIXIN
        { name: '从微信导入', backgroundColor: '#0BB955', color: '#FFFFFF', emit: 'export', src: '/static/image/icon_wechat@2x.png' },
        // #endif
        { name: '保存', isLinearBg: true }
      ]
    }
  },
  mounted() {
    this.height = uni.getSystemInfoSync().windowHeight - getNavHeight() - uni.upx2px(150)
  },
  onLoad(option) {
    const { type, id } = option
    this.id = id
    this.type = type
    var title = type == 'edit' ? '编辑收货地址' : '添加收货地址'
    uni.setNavigationBarTitle({ title })
    if (id) this.getAddressDetail(id)
  },
  methods: {
    // 从微信导入
    handleExportFromWX() {
      const that = this
      uni.authorize({
        scope: 'scope.address',
        success: (result) => {
          that.getUserWXAddress()
        }
      })
    },
    // 获取用户微信收货地址
    getUserWXAddress() {
      const that = this
      uni.chooseAddress({
        success(res) {
          const params = { addressNames: [res.provinceName, res.cityName, res.countyName] }
          that.getAddressDetailsByWXExport(params)
          that.userInfo.name = res.userName
          that.userInfo.detailAddress = res.detailInfo
          if (/^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(res.telNumber)) {
            that.userInfo.mobile = res.telNumber
          } else {
            that.userInfo.office_phone = res.telNumber
          }
        }
      })
    },
    // 根绝微信导入地址获取地址详情
    async getAddressDetailsByWXExport(params) {
      const res = await queryAddressLibraryInfo(params)
      if (res.code == 0) {
        const [areaDetail, cityDetail, provinceDetail] = res.data.addressLibraryDtoList
        this.cityInfo = {
          provinceId: provinceDetail.address_id,
          provinceName: provinceDetail.name,
          provinceCode: provinceDetail.code,
          cityId: cityDetail.address_id,
          cityName: cityDetail.name,
          cityCode: cityDetail.code,
          districtId: areaDetail.address_id,
          areaName: areaDetail.name,
          districtCode: areaDetail.code,
          streetId: '',
          streetName: '',
          streetCode: '',
        }
        const { provinceName, cityName, areaName, streetName } = this.cityInfo
        this.userInfo.address = `${provinceName} ${cityName} ${areaName} ${streetName}`
      } else {
        this.$u.toast(res.msg)
      }
    },
    // 删除地址
    handleDeleteAddress() {
      this.$u.throttle(async() => {
        const { customerId, memberId } = this.vuex_memberInfo
        const params = {
          memberId: memberId,
          shipAddId: this.ship_add_id,
          customer_id: customerId
        }
        const res = await deleteAddress(params)
        if (res.errorCode == 1) {
          this.showModal = false
          this.$u.toast('删除成功')
          uni.navigateTo({
            url: '/address/addressList'
          })
        }
      }, 1000)
    },
    // 打开地图定位
    handleOpenMap() {
      uni.navigateTo({
        url: `/preview-map/mapWebview?domain=${this.vuex_baseURL.webUrl}`
      })
    },
    showRegion() {
      this.regionShow = true
    },
    closeRegionFn() {
      this.regionShow = false
    },
    getParams(e) {
      if (e.length > 3) {
        this.cityInfo = {
          provinceId: e[0].id,
          provinceName: e[0].name,
          provinceCode: e[0].keyName,
          cityId: e[1].id,
          cityName: e[1].name,
          cityCode: e[1].keyName,
          districtId: e[2].id,
          areaName: e[2].name,
          districtCode: e[2].keyName,
          streetId: e[3].id,
          streetName: e[3].name,
          streetCode: e[3].keyName,
        }
        const { provinceName, cityName, areaName, streetName } = this.cityInfo
        this.userInfo.address = `${provinceName} ${cityName} ${areaName} ${streetName}`
        this.regionShow = false
      }
    },
    async addressAdd() {
      for (var item in this.userInfo) {
        if (item !== 'office_phone' && !this.userInfo[item]) {
          return this.$u.toast('请输入完整信息');
        }
      }
      var moblie = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
      var phone = /^((0\d{2,3})-)?(\d{7,8})$/;
      if (!moblie.test(this.userInfo.mobile)) {
        return this.$u.toast('请输入正确的手机号');
      }
      if (!!this.userInfo.office_phone && !phone.test(this.userInfo.office_phone)) {
        return this.$u.toast('请输入正确的固定电话');
      }
      const { accountType = 20 } = this.vuex_memberInfo || {}
      const { customerId, memberId } = this.vuex_memberInfo
      var str = [
        {
          mobile: this.userInfo.mobile,
          name: this.userInfo.name,
          status: 10,
          addressId: this.id,
          id: 0,
          receiverId: 0
        }
      ]
      const params = {
        shipAddId: this.id,
        ...this.cityInfo,
        detailAddress: this.userInfo.detailAddress,
        account_type: accountType,
        shipAddPersonJson: JSON.stringify(str),
        isDefaultAddress: this.isDefaultAddress ? 1 : 2,
        officePhone: this.userInfo.office_phone,
        customer_id: customerId,
        memberId,
        member_id: memberId
      }
      if (!this.id) delete params.shipAddId
      if (!this.isDefaultAddress) delete params.isDefaultAddress
      const res = this.id ? await editAddress(params) : await saveAddress(params)
      if (res.errorCode == 0) {
        this.$u.toast(res.errorMessage);
        setTimeout(() => {
          uni.navigateBack({ delta: 1 })
        }, 1000)
      } else {
        this.$u.toast(res.errorMessage);
      }
    },
    async getAddressDetail(id) {
      const { accountType, memberId, customerId } = this.vuex_memberInfo
      const { customerCode } = this.vuex_crmCustomerInfos ?? {}
      const params = {
        member_id: memberId,
        memberId,
        shipAddId: id,
        account_type: accountType,
        customer_id: customerId,
        customer_code: customerCode
      }
      const res = await getAddressDetail(params)
      if (res.errorCode == 1) {
        const { addressPersonList, detail_address, provinceName, province_id, province_code, cityName, city_code, city_id,
          areaName, district_code, district_id, streetName, street_id, street_code, office_phone, is_default, ship_add_id } = res.shippingAddress
        this.ship_add_id = ship_add_id
        this.userInfo = {
          name: addressPersonList[0].receiver_name,
          mobile: addressPersonList[0].mobile,
          office_phone,
          address: `${provinceName} ${cityName} ${areaName} ${streetName}`,
          detailAddress: detail_address
        }
        this.isDefaultAddress = is_default == '1'
        this.cityInfo = {
          provinceId: province_id,
          provinceName,
          provinceCode: province_code,
          cityName,
          cityCode: city_code,
          cityId: city_id,
          districtId: district_id,
          areaName,
          districtCode: district_code,
          streetId: street_id,
          streetName,
          streetCode: street_code
        }
      }
    }
  }
}
</script>

<style lang="scss">
/deep/ .u-line {
  border-bottom: 2rpx solid $uni-border-gray !important;
}
/deep/ .u-textarea__field {
  color: #303133 !important;
}
.addressEdit {
  padding: 16rpx 32rpx;
  box-sizing: border-box;
  .defaultSw {
    padding: 32rpx 0rpx;
    box-sizing: border-box;
    border-top:2rpx solid $uni-border-gray;
    view {
      display: flex;
      justify-content: space-between;
      align-content: center;
      align-items: center;
      font-weight:normal;
      color: $uni-text-color;
      font-size:$uni-font-size-base;
    }
    text {
      color: #808080;
      font-weight: normal;
      font-size:$uni-font-size-sm;
    }
  }
  .regionPopup {
    .title {
      width: 100%;
      height: 88rpx;
      padding: 0rpx 32rpx;
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
      align-items: center;
      align-content: center;
      font-weight: bold;
      color: $uni-text-color;
      font-size:$uni-font-size-base;
      border-bottom:2rpx solid $uni-border-gray;
      image {
        height: 48rpx;
        width: 48rpx;
      }
      .icon-close{
        font-size: 48rpx;
        color: #d3d3d3;
        font-weight: normal;
      }
    }
  }
  .content {
    background:$uni-bg-color;
    padding: 10rpx 32rpx;
    box-sizing: border-box;
    border-radius:$uni-border-radius-default;
  }
  .footerFaker {
    width: 100%;
    height: 160rpx;
  }
  .footer {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 160rpx;
    box-sizing: border-box;
    display: flex;
    padding: 12rpx 48rpx 0;
    background:$uni-bg-color;
    .button {
      width: 624rpx;
      height: 64rpx;
      background: linear-gradient(128.8deg, rgba(255,121,95,1) 0%, rgba(238,61,26,1) 100%);
      font-weight: normal;
      margin: 0 auto;
      display: flex;
      justify-content: center;
      align-content: center;
      align-items: center;
      border-radius:$uni-border-radius-default;
      font-size:$uni-font-size-base;
      color:$uni-text-color-inverse;
    }
    .delete-btn {
      background: $uni-bg-color;
      color:$uni-text-color;
      border: 1rpx solid rgba(222,222,222,1);
    }
    .delete-btn, .add-btn {
      width: 314rpx;
    }
  }
  .address_placeholder {
    color: $uni-text-color-disable;
  }
  .address_placeholder, .address_content {
    min-width: 354rpx;
  }
  .address-wrap {
    display: flex;
    align-items: baseline;
    .locate_wrap {
      display: flex;
      align-items: center;
      margin-left: 24rpx;
      line-height: 42rpx;
      .locate_label {
        width: 56rpx;
        height: 40rpx;
        text-align: left;
        color: $uni-orange;
        font-size:$uni-font-size-base;
      }
      .location-icon{
        margin-left: 4rpx;
        top: 4rpx;
        position: relative;
        font-size: $uni-font-size-lg;
        color: $uni-text-color-orange;
      }
    }
  }
  .warn_tips {
    color: $uni-orange;
  }
}
.content {
  /deep/.u-textarea {
    padding: 0rpx !important;
  }
  /deep/ .u-form-item {
    padding: 10rpx 0rpx;
  }
}
</style>
